package com.wes.dsptest;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.media.VolumeShaper;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.wes.dsptest.audioalarm.AudioFragment;
import com.wes.dsptest.data.TinySharedPreferences;
import com.wes.dsptest.dspcontrol.DspConfigFragment;
import com.wes.dsptest.info.InfoFragment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.flyaudio.dsp.IdspInterface;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainDSPTool";
    private ViewPager2 viewpager;
    private ImageView ivDspConfig, ivAudio, ivTest, ivInfo, ivQuit, ivCurrent;
    private static IdspInterface mdspInterface;

    private static final int  REQUEST_CODE = 1112;

    private String[] mPermissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WAKE_LOCK,
            Manifest.permission.SYSTEM_ALERT_WINDOW,
    };

    private String FileMusicName = "Anull";
    private int curPosition = 0;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG,"onCreate");
        setContentView(R.layout.activity_main);
        //1
        initPersmission();
        //2
        initData();
        //3
        initViewConfig();
        initTabView();
        initViewPager();

        initDiskInfo();
        initTest();
    }

    private void initDiskInfo() {
        try {
            File partitionsFile = new File("/proc/partitions");
            BufferedReader reader = new BufferedReader(new FileReader(partitionsFile));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.trim().split("\\s+");
                if (fields.length >= 4 && fields[3].startsWith("sd")) {
                    // Found a hard disk partition
                    String deviceName = fields[3];
                    long blockSize = Long.parseLong(fields[2]);
                    long numBlocks = Long.parseLong(fields[1]);
                    long size = blockSize * numBlocks;
                    Log.d(TAG, "Found hard disk " + deviceName + " with size " + size + " bytes");
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void initTest() {
        UsbUtils usbUtils = new UsbUtils();
        Log.i(TAG, "disk exist: "+usbUtils.isHardDiskExist());
        Log.i(TAG, "disk info: "+usbUtils.getDiskInfo());
    }

    private void initViewConfig() {
        Configuration configuration = getResources().getConfiguration();
        int orientaion = configuration.orientation;
        if(orientaion == Configuration.ORIENTATION_LANDSCAPE){
            Log.i(TAG, "screen orientation Landscape");
        } else if(orientaion == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    private boolean isLackPermission() {
        for (String permission : mPermissions) {
            if ((ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED))
            {
                return true;
            }
            else if(permission == Manifest.permission.SYSTEM_ALERT_WINDOW){
                // 如果没有读取联系人的权限，则申请权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, REQUEST_CODE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    intent.setData(Uri.parse("package:" + this.getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    this.startActivity(intent);
                }
            }
            else {
                ActivityCompat.requestPermissions(this, mPermissions, REQUEST_CODE);
            }
        }
        return false;
    }

    private void initPersmission() {
        isLackPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted
            } else {
                // Permission denied
            }
        }
    }

    private void initData() {
        TinySharedPreferences tsp = TinySharedPreferences.instance(this);
        curPosition = tsp.getIntValue("navTab", 0);
        FileMusicName = tsp.getStringValue("MusicName", FileMusicName);
    }

    private void setSavePager(int posiion) {
        TinySharedPreferences tsp = TinySharedPreferences.instance(this);
        tsp.setIntValue("navTab", posiion);
    }

    private void initTabView() {
        ivDspConfig = findViewById(R.id.iv_dspconfig);
        ivAudio = findViewById(R.id.iv_audio);
        ivInfo = findViewById(R.id.iv_info);
        ivTest = findViewById(R.id.iv_test);
        ivQuit = findViewById(R.id.iv_quit);
        ivDspConfig.setOnClickListener(this);
        ivAudio.setOnClickListener(this);
        ivInfo.setOnClickListener(this);
        ivTest.setOnClickListener(this);
        ivQuit.setOnClickListener(this);
        ivCurrent = ivDspConfig;

    }

    private void initViewPager() {
        viewpager = findViewById(R.id.vp_fragment);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(DspConfigFragment.newInstance("DSP"));
        fragments.add(AudioFragment.newInstance(FileMusicName));
        fragments.add(TestFragment.newInstance("测试界面"));
        fragments.add(InfoFragment.newInstance());
        MainViewPagerAdapter mVPAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
        viewpager.setAdapter(mVPAdapter);
        viewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changePage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });

        //init
        changePage(curPosition);
        viewpager.setCurrentItem(curPosition, false);
    }

    private void changePage(int position) {
        ivCurrent.setSelected(false);
        int curPager = 0;
        switch (position) {
            case R.id.iv_dspconfig:
                viewpager.setCurrentItem(0);
            case 0:
                curPager = 0;
                ivCurrent = ivDspConfig;
                ivDspConfig.setSelected(true);
                break;
            case R.id.iv_audio:
                viewpager.setCurrentItem(1);
            case 1:
                curPager = 1;
                ivCurrent = ivAudio;
                ivAudio.setSelected(true);
                break;
            case R.id.iv_test:
                viewpager.setCurrentItem(2);
            case 2:
                curPager = 2;
                ivCurrent = ivTest;
                ivTest.setSelected(true);
                break;
            case R.id.iv_info:
                viewpager.setCurrentItem(3);
            case 3:
                curPager = 3;
                ivCurrent = ivInfo;
                ivInfo.setSelected(true);
                break;
            case R.id.llQuit:
            case R.id.iv_quit:
                finish();
                break;
        }
        setSavePager(curPager);
    }

    @Override
    public void onClick(View view) {
        changePage(view.getId());

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"onStart");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG,"onRestart");
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,"onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,"onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,"onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");

    }
}